// Chart rendering and management

let radarChart = null;
let qpsChart = null;
let latencyChart = null;
let powerChart = null;
let efficiencyChart = null;

// Color palette for charts
const COLORS = [
    '#3498db', // blue
    '#e74c3c', // red
    '#2ecc71', // green
    '#f39c12', // orange
    '#9b59b6', // purple
    '#1abc9c', // turquoise
    '#34495e', // dark gray
    '#e67e22', // dark orange
];

/**
 * Update all charts with new score data
 */
function updateCharts(data) {
    updateRadarChart(data);
    updateQPSChart(data);
    updateLatencyChart(data);
    updatePowerChart(data);
    updateEfficiencyChart(data);
}

/**
 * Update radar chart showing 4 dimensions
 */
function updateRadarChart(data) {
    const ctx = document.getElementById('radarChart').getContext('2d');
    
    // Limit to top 5 devices for clarity
    const topDevices = data.scores.slice(0, 5);
    
    // Build datasets based on whether power data is available
    const datasets = topDevices.map((score, index) => {
        // If no power data, skip efficiency_score in the data array
        const dataPoints = data.has_power 
            ? [
                score.performance_score,
                score.efficiency_score || 0,
                score.resource_score,
                score.stability_score
              ]
            : [
                score.performance_score,
                score.resource_score,
                score.stability_score
              ];
        
        return {
            label: score.id,
            data: dataPoints,
            backgroundColor: hexToRGBA(COLORS[index % COLORS.length], 0.2),
            borderColor: COLORS[index % COLORS.length],
            borderWidth: 2,
            pointBackgroundColor: COLORS[index % COLORS.length],
            pointBorderColor: '#fff',
            pointHoverBackgroundColor: '#fff',
            pointHoverBorderColor: COLORS[index % COLORS.length]
        };
    });
    
    const chartData = {
        labels: data.has_power ? ['性能', '能效', '资源', '稳定性'] : ['性能', '资源', '稳定性'],
        datasets: datasets
    };
    
    const config = {
        type: 'radar',
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: true,
            scales: {
                r: {
                    beginAtZero: true,
                    suggestedMin: 0,
                    suggestedMax: 200,
                    ticks: {
                        stepSize: 50
                    }
                }
            },
            plugins: {
                legend: {
                    position: 'bottom'
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return context.dataset.label + ': ' + context.parsed.r.toFixed(2);
                        }
                    }
                }
            }
        }
    };
    
    if (radarChart) {
        radarChart.destroy();
    }
    radarChart = new Chart(ctx, config);
}

/**
 * Update QPS comparison bar chart
 */
function updateQPSChart(data) {
    const ctx = document.getElementById('qpsChart').getContext('2d');
    
    const labels = data.scores.map(s => s.id);
    const qpsData = data.scores.map(s => s.stats.qps || 0);
    
    const chartData = {
        labels: labels,
        datasets: [{
            label: 'QPS (查询/秒)',
            data: qpsData,
            backgroundColor: COLORS.slice(0, data.scores.length),
            borderColor: COLORS.slice(0, data.scores.length).map(c => c),
            borderWidth: 1
        }]
    };
    
    const config = {
        type: 'bar',
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return 'QPS: ' + context.parsed.y.toFixed(2);
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'QPS'
                    }
                }
            }
        }
    };
    
    if (qpsChart) {
        qpsChart.destroy();
    }
    qpsChart = new Chart(ctx, config);
}

/**
 * Update latency comparison chart
 */
function updateLatencyChart(data) {
    const ctx = document.getElementById('latencyChart').getContext('2d');
    
    const labels = data.scores.map(s => s.id);
    const avgLatency = data.scores.map(s => s.stats.lat_avg_ms || 0);
    const p99Latency = data.scores.map(s => s.stats.p99_ms || 0);
    
    const chartData = {
        labels: labels,
        datasets: [
            {
                label: '平均延迟 (ms)',
                data: avgLatency,
                backgroundColor: hexToRGBA('#3498db', 0.7),
                borderColor: '#3498db',
                borderWidth: 1
            },
            {
                label: 'P99 延迟 (ms)',
                data: p99Latency,
                backgroundColor: hexToRGBA('#e74c3c', 0.7),
                borderColor: '#e74c3c',
                borderWidth: 1
            }
        ]
    };
    
    const config = {
        type: 'bar',
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'top'
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return context.dataset.label + ': ' + context.parsed.y.toFixed(2) + ' ms';
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: '延迟 (ms)'
                    }
                }
            }
        }
    };
    
    if (latencyChart) {
        latencyChart.destroy();
    }
    latencyChart = new Chart(ctx, config);
}

/**
 * Update power consumption chart
 */
function updatePowerChart(data) {
    const ctx = document.getElementById('powerChart').getContext('2d');
    
    // Check if power data is available
    const hasPowerData = data.scores.some(s => s.stats.perf_per_W > 0);
    
    if (!hasPowerData) {
        // Display message
        if (powerChart) {
            powerChart.destroy();
        }
        ctx.font = '16px Arial';
        ctx.fillStyle = '#666';
        ctx.textAlign = 'center';
        ctx.fillText('功耗数据不可用', ctx.canvas.width / 2, ctx.canvas.height / 2);
        return;
    }
    
    const labels = data.scores.map(s => s.id);
    const powerData = data.scores.map(s => {
        // Estimate power from perf_per_W if available
        const perfPerW = s.stats.perf_per_W || 0;
        const qps = s.stats.qps || 0;
        return perfPerW > 0 ? qps / perfPerW : 0;
    });
    
    const chartData = {
        labels: labels,
        datasets: [{
            label: '平均功耗 (W)',
            data: powerData,
            backgroundColor: COLORS.slice(0, data.scores.length).map(c => hexToRGBA(c, 0.7)),
            borderColor: COLORS.slice(0, data.scores.length),
            borderWidth: 1
        }]
    };
    
    const config = {
        type: 'bar',
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return '功耗: ' + context.parsed.y.toFixed(2) + ' W';
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: '功耗 (W)'
                    }
                }
            }
        }
    };
    
    if (powerChart) {
        powerChart.destroy();
    }
    powerChart = new Chart(ctx, config);
}

/**
 * Update efficiency ranking chart
 */
function updateEfficiencyChart(data) {
    const ctx = document.getElementById('efficiencyChart').getContext('2d');
    
    // Check if power data is available
    const hasPowerData = data.scores.some(s => s.stats.perf_per_W > 0);
    
    if (!hasPowerData) {
        // Display message
        if (efficiencyChart) {
            efficiencyChart.destroy();
        }
        ctx.font = '16px Arial';
        ctx.fillStyle = '#666';
        ctx.textAlign = 'center';
        ctx.fillText('能效数据不可用', ctx.canvas.width / 2, ctx.canvas.height / 2);
        return;
    }
    
    // Sort by efficiency
    const sortedScores = [...data.scores].sort((a, b) => {
        const aEff = a.stats.perf_per_W || 0;
        const bEff = b.stats.perf_per_W || 0;
        return bEff - aEff;
    });
    
    const labels = sortedScores.map(s => s.id);
    const efficiencyData = sortedScores.map(s => s.stats.perf_per_W || 0);
    
    const chartData = {
        labels: labels,
        datasets: [{
            label: '能效 (QPS/W)',
            data: efficiencyData,
            backgroundColor: efficiencyData.map((v, i) => {
                if (i === 0) return hexToRGBA('#2ecc71', 0.8); // Best
                if (i === efficiencyData.length - 1) return hexToRGBA('#e74c3c', 0.6); // Worst
                return hexToRGBA('#3498db', 0.7); // Others
            }),
            borderColor: efficiencyData.map((v, i) => {
                if (i === 0) return '#2ecc71';
                if (i === efficiencyData.length - 1) return '#e74c3c';
                return '#3498db';
            }),
            borderWidth: 1
        }]
    };
    
    const config = {
        type: 'bar',
        data: chartData,
        options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return '能效: ' + context.parsed.x.toFixed(2) + ' QPS/W';
                        }
                    }
                }
            },
            scales: {
                x: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: '能效 (QPS/W)'
                    }
                }
            }
        }
    };
    
    if (efficiencyChart) {
        efficiencyChart.destroy();
    }
    efficiencyChart = new Chart(ctx, config);
}

/**
 * Utility: Convert hex color to RGBA
 */
function hexToRGBA(hex, alpha) {
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}

